//
//  AppDelegate.m
//  Adorable_Things
//
//  Created by ybq on 16/1/9.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "AppDelegate.h"
#import "ATRootTabBarController.h"
#import "UMSocial.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "XGPush.h"
#import "XGSetting.h"
#import "JDSideMenu.h"
#import "ATDrawerViewController.h"
#import "UMSocialSinaSSOHandler.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

/*
 
 微博开发平台：App key：1710474392
            App secret：3a605f150b8e1957e01495d2541693e9
 
 腾讯：APP ID：1105039237
      APP KEY：hR8K1PCaOrjA7v2g
 设置Xcode的url scheme格式为 QQ41DD8F85  
 */

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // 抽屉效果
    ATRootTabBarController *tabBarVC = [[ATRootTabBarController alloc] init];
    ATDrawerViewController *drawerVC = [[ATDrawerViewController alloc]init];
    JDSideMenu *sideMenu = [[JDSideMenu alloc] initWithContentController:tabBarVC menuController:drawerVC];
    self.window.rootViewController = sideMenu;
    
    [UMSocialData setAppKey:@"56971506e0f55abee6001622"];
    
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"1710474392" RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
     [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    [UMSocialQQHandler setQQWithAppId:@"1105039237" appKey:@"hR8K1PCaOrjA7v2g" url:@"http://www.menghuoapp.com/item/36954"];
    

    //审核通过后 ！！！！设置微信AppId、appSecret，分享url
    [UMSocialWechatHandler setWXAppId:@"wx12406804e52af725" appSecret:@"87d84f826dd20a1764459b89c91be9e4" url:@"http://www.menghuoapp.com/item/36954"];
    
   // [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
    
    [XGPush startApp:1105039237 appKey:@"hR8K1PCaOrjA7v2g"];
    
    
    // iOS8之后注册通知方法改了, 所以需要进行版本判断
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f) {
        
        // 注册设置: 角标, 声音, 提示框
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil]];
        // 注册通知
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
    }
    else{
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
        
        
        
    }
    // 请求新的token
    [self refreshToken];

    return YES;
}

- (void)refreshToken
{
    ATUserManager *manager = [ATUserManager shareManager];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:kUserInfor];
    manager.auth_token = dic[@"auth_token"];
    manager.nickname = dic[@"nickname"] ;
    manager.avatar = dic[@"avatar"] ;
    if (manager.auth_token.length == 0) {
        manager.auth_token = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTQxMzY2NTUsInVzZXJfaWQiOjIzMTA1fQ._k8_uSO33Wn8d4N8HTYXsw8yhA4B7cm66xQ07SlTV4E";
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session POST:@"http://api.menghuoapp.com/v1/token/refresh" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        manager.auth_token = responseObject[@"data"];
        // 写入文件
        NSMutableDictionary *newDic = [NSMutableDictionary dictionary];
        newDic[@"isLogin"] = [NSString stringWithFormat:@"%ld",manager.isLogin];
        newDic[@"auth_token"] = manager.auth_token;
        newDic[@"nickname"] = manager.nickname;
        newDic[@"avatar"] = manager.avatar;
        [newDic writeToFile:kUserInfor atomically:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
   
}

// 注册成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [XGPush registerDevice:deviceToken];
}
// 注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"error:%@", error);
}
// 接收通知的触发方法
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
   
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
